local paiyi = fk.CreateSkill {
  name = "hx__paiyi",
}

local HX = require "packages/huixiangkill/hxfs"

paiyi:addEffect("active", {
  anim_type = "offensive",
  expand_pile = "hxzhaohua__zhonghui_power",
  prompt = function(self, player, selected_cards, selected_targets)
    local n = math.max(#player:getPile("hxzhaohua__zhonghui_power") - 1, 1)
    if self.interaction.data == "draw_card" then
      return "#hx__paiyi_draw:::"..n
    else
      return "#hx__paiyi_damage:::"..n
    end
  end,
  card_num = 1,
  min_target_num = 1,
  max_target_num = function(self, player)
    if self.interaction.data == "draw_card" then
      return 1
    else
      return math.max(#player:getPile("hxzhaohua__zhonghui_power") - 1, 1)
    end
  end,
  interaction = function(self, player)
    return UI.ComboBox { choices = { "Damage","draw_card"}, all_choices = { "Damage","draw_card"} }
  end,
  can_use = function(self, player)
    return #player:getPile("hxzhaohua__zhonghui_power") > 0
  end,
  card_filter = function(self, player, to_select, selected)
    return #selected == 0 and table.contains(player:getPile("hxzhaohua__zhonghui_power"), to_select)
  end,
  target_filter = function(self, player, to_select, selected)
    if self.interaction.data == "draw_card" then
      return #selected == 0
    else
      return #selected < math.max(#player:getPile("hxzhaohua__zhonghui_power") - 1, 1)
    end
  end,
  on_use = function(self, room, effect)
    local player = effect.from
    room:moveCards({
      from = player,
      ids = effect.cards,
      toArea = Card.DiscardPile,
      moveReason = fk.ReasonPutIntoDiscardPile,
      skillName = paiyi.name,
    })
    if player.dead then return end
    if self.interaction.data == "draw_card" then
      local target = effect.tos[1]
      if not target.dead then
        target:drawCards(math.max(#player:getPile("hxzhaohua__zhonghui_power"), 1), paiyi.name)
      end
    else
      local tos = table.simpleClone(effect.tos)
      room:sortByAction(tos)
      for _, p in ipairs(tos) do
        if not p.dead then
          room:damage{
            from = player,
            to = p,
            damage = 1,
            skillName = paiyi.name,
          }
        end
      end
    end
    if player.dead then return end
    if  table.every(room.alive_players, function (p)
      return p:getHandcardNum() >= player:getHandcardNum()
    end) and #player:getPile("hxzhaohua__zhonghui_power") == 0 then
      HX.SetTheSkillTimes(room, player, "hx__zili", 0)
    end
    if #player:getCardIds("h") > #player:getPile("hxzhaohua__zhonghui_power") then
      room:invalidateSkill(player, paiyi.name, "-phase")
    end
  end,
})

return paiyi
